using JGSY.CMS.LowCode.Platform.Infrastructure.CmsDbContext;
using JGSY.CMS.LowCode.Platform.Infrastructure.Configuration;
using JGSY.CMS.LowCode.Platform.Infrastructure.Services;
using JGSY.CMS.LowCode.Platform.Application.Interfaces;
using JGSY.CMS.LowCode.Platform.Application.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Pomelo.EntityFrameworkCore.MySql.Infrastructure;

namespace JGSY.CMS.LowCode.Platform.Infrastructure{
    /// <summary>
    /// 数据库选项构建器辅助类
    /// 提供根据不同数据库类型配置DbContext选项的统一方法
    /// </summary>
    internal static class DatabaseOptionsBuilderHelper
    {
        /// <summary>
        /// 根据数据库类型配置DbContext选项
        /// 支持SqlServer、MySql、PostgreSQL和SQLite数据库
        /// </summary>
        /// <param name="optionsBuilder">DbContext选项构建器</param>
        /// <param name="dbType">数据库类型标识符</param>
        /// <param name="connStr">数据库连接字符串</param>
        public static void ConfigureOptions(DbContextOptionsBuilder optionsBuilder, string dbType, string connStr)
        {
            // 使用统一配置处理器
            UnifiedConfigurationProcessor.ConfigureDatabaseOptions(optionsBuilder, dbType, connStr);
        }
    }
 
    /// <summary>
    /// 数据库服务集合扩展
    /// 提供数据库上下文注册和配置的扩展方法
    /// </summary>
    public static class DatabaseServiceCollectionExtensions
    {
        /// <summary>
        /// 注册低代码平台数据库上下文 - 优化为延迟连接
        /// 根据配置文件中的DatabaseType和连接字符串自动配置数据库提供程序，仅支持生产级数据库
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <param name="configuration">配置对象</param>
        /// <returns>配置后的服务集合</returns>
        public static IServiceCollection AddLowCodeDbContext(this IServiceCollection services, IConfiguration configuration)
        {
            var mapper = new JGSY.CMS.LowCode.Platform.Infrastructure.Configuration.AppSettingsMapper(configuration);
            var databaseConfig = mapper.Bind<JGSY.CMS.LowCode.Platform.Infrastructure.Configuration.Models.DatabaseConfiguration>("");
            
            var dbType = databaseConfig.DatabaseType ?? "Postgres"; // 默认PostgreSQL
            var connStr = UnifiedConfigurationProcessor.GetDatabaseConnectionString(dbType);

            // 注册多租户服务
            services.AddScoped<ITenantContext, TenantContext>();
            services.AddScoped<ITenantService, TenantService>();

            // 延迟数据库连接 - 只注册服务，不立即连接
            services.AddDbContext<LowCodeDbContext>((serviceProvider, options) =>
            {
                DatabaseOptionsBuilderHelper.ConfigureOptions(options, dbType, connStr);
                
                // 优化连接池和超时设置
                options.EnableServiceProviderCaching(true);
                options.EnableSensitiveDataLogging(false); // 生产环境关闭敏感数据日志
            }, ServiceLifetime.Scoped); // 明确指定生命周期
            
            return services;
        }
    }
}
